package com.techstar.ats.service;

import java.time.LocalDate;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import lombok.RequiredArgsConstructor;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.techstar.ats.AtsProperties;
import com.techstar.ats.ConnectProperties;
import com.techstar.ats.MessageType;
import com.techstar.ats.dxp.history.req.F21LoadHistoryTgData;
import com.techstar.ats.type.TgType;
import com.techstar.ats.utils.NettyBeanHelper;

@Service
@RequiredArgsConstructor
public class AtsService {
	private static final Cache<Integer, Queue<Object>> cmdCache = CacheBuilder.newBuilder()
		.expireAfterWrite(30L, TimeUnit.MINUTES)
		.build();

	private final AtsProperties atsProperties;

	public void f12ReportAsk() {
		for(ConnectProperties p : this.atsProperties.getConnects()) {
			if(p.isLive()) {
			}
		}
	}

	public void f18AlarmAsk() {
		for(ConnectProperties p : this.atsProperties.getConnects()) {
			if(p.isLive()) {
			}
		}
	}

	@Scheduled(fixedDelay = 10000L)
	public void scheduler() {
		for(ConnectProperties p : this.atsProperties.getConnects()) {
			if(!p.isLive()) {
				Queue<Object> queue = cmdCache.getIfPresent(p.getLine());
				if(null != queue) {
					Object msg = queue.poll();
					if(null != msg) {
						boolean isSuccess = NettyBeanHelper.send(p.getLine(), msg);
						if(!isSuccess) {
							queue.add(msg);
						}
					}
				}
			}
		}

	}

	public void f21LoadHistoryTgData() {
		LocalDate today = LocalDate.now();
		LocalDate yesterday = today.minusDays(1);
		for(ConnectProperties p : this.atsProperties.getConnects()) {
			if(!p.isLive()) {
				F21LoadHistoryTgData t1 = new F21LoadHistoryTgData();
				t1.id = MessageType.LOAD_HISTORY_TG_DATA.value();
				t1.type = TgType.PLAN;
				t1.datetime = today.atStartOfDay();
				this.addCache(p.getLine(), t1, t1.datetime.toLocalDate(), "inused");

				F21LoadHistoryTgData t2 = new F21LoadHistoryTgData();
				t2.id = MessageType.LOAD_HISTORY_TG_DATA.value();
				t2.type = TgType.ACTUAL;
				t2.datetime = yesterday.atStartOfDay();
				this.addCache(p.getLine(), t2, t2.datetime.toLocalDate(), "history");
			}
		}
	}

	public void addCache(int line, Object msg, LocalDate date, String mode) {
		Queue<Object> queue = cmdCache.getIfPresent(line);
		if(null == queue) {
			queue = new LinkedBlockingQueue<>();
			cmdCache.put(line, queue);
		}

		queue.add(msg);
	}
}
